package com.sky.mytask;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class MyTask {

    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 * * * * ? ")
    public void payTimeOut(){
        log.info("每分钟执行一次支付超时");
        LocalDateTime now = LocalDateTime.now();
        //now - 15min > order time  -> 超时
        LocalDateTime time = now.plusMinutes(-15);
        List<Orders> OrdersOut = orderMapper.getByStatusandOrderTimelt(Orders.PENDING_PAYMENT, time);
        for (Orders orders : OrdersOut) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("支付超时");
            orderMapper.update(orders);
        }
    }

    @Scheduled(cron = "0 0 1 * * ? ")
    //每天凌晨1点自动完成
    public void deliverOut(){ //派送自动完成
        log.info("每秒执行一次送达未完成");
        LocalDateTime now = LocalDateTime.now();
        //所以凌晨1点  - 1 则是第二天 就能找到昨天的订单
        LocalDateTime  time = now.plusMinutes(-60);
        List<Orders> orderslist = orderMapper.getByStatusandOrderTimelt(Orders.DELIVERY_IN_PROGRESS, time);
        for (Orders orders : orderslist) {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }
    }
}
